/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.npmpackage.core.npmsetting;

import com.inspur.edp.web.common.environment.ExecuteEnvironment;
import com.inspur.edp.web.npmpackage.api.entity.NpmInstallParameter;
import com.inspur.edp.web.npmpackage.api.entity.settings.NpmRepository;
import com.inspur.edp.web.npmpackage.api.entity.settings.NpmSettings;


/**
 * npm setting 转换成npm install parameter
 *
 * @author guozhiqi
 */
public class NpmSettingConvertor {
    public static NpmInstallParameter convertFromNpmSetting(NpmSettings npmSettings) {
        NpmInstallParameter npmInstallParameter = new NpmInstallParameter();
        String currentNpmSettingMode = npmSettings.getSettingMode();
        NpmRepository[] repositories = npmSettings.getSettingConfig().getRepositories();

        NpmRepository currentRepository = null;
        for (NpmRepository repository : repositories) {
            String tempSettingMode = repository.getId();
            if (tempSettingMode.equals(currentNpmSettingMode)) {
                currentRepository = repository;
            }
        }
        // 如果获取到的仓库实例为空
        if (currentRepository == null) {
            throw new RuntimeException("未获取到npm配置仓库实例");
        }

        npmInstallParameter.setUserName(currentRepository.getUserName());
        npmInstallParameter.setPassword(currentRepository.getPassword());
        npmInstallParameter.setRegistry(currentRepository.getUrl());
        npmInstallParameter.setExecuteEnvironment(ExecuteEnvironment.Design);
        npmInstallParameter.setUpdatePolicy(currentRepository.getUpdatePolicy());
        npmInstallParameter.setUpdateAll(true);
        npmInstallParameter.setOfflineMode(npmSettings.isOffline());

        return npmInstallParameter;
    }
}
